//
//  HomeViewController.m
//  wifi4.2
//
//  Created by 郭四虎 on 15/11/10.
//  Copyright © 2015年 YouKu. All rights reserved.
//
#import <CoreLocation/CoreLocation.h>
#import "HomeViewController.h"
#import "HomeDetailViewController.h"
#import "SDCycleScrollView.h"
#import "adViewController.h"
#import "BannerModel.h"
#import "ServerModel.h"
#import "ServerCell.h"
#import "AppDelegate.h"
@interface HomeViewController ()<SDCycleScrollViewDelegate,CLLocationManagerDelegate,GDTSplashAdDelegate,UITableViewDelegate,UITableViewDataSource>
{
    NSMutableArray *_slideArr;
    NSMutableArray *_loadingArr;
    
    NSURLConnection *_uc;
    
    UIButton *_carBtn;
    UIButton *_planBtn;
    UILabel *_desc;
    UIView *_backView;
    UIImageView *_adIma;
    
    BOOL _haveClicked;
    BOOL _isThirdAD;
    BOOL _shouldHide;
    
    BOOL _statusBarHide;
    
    CGFloat _addHeight;
    
    SDCycleScrollView *scrollView;
    CLLocationManager *_manager;
    
    BOOL _isError;
    
    UIImage *_launchimage;
    GDTSplashAd *_splash;
    
    UIWindow *fK;
    
    NSInteger _nextKey;
    UIScrollView *_descScroll;
}

@property (weak, nonatomic) IBOutlet UIView *scroll;
@property (strong, nonatomic) UIView *headerVi;
@property (strong, nonatomic) NSMutableArray *dataArr;
@property (strong, nonatomic) UITableView *table;

@end

@implementation HomeViewController

//- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
//{
//    if ([keyPath isEqualToString:@"count"]) {
//        
//    }
//    NSLog(@"%@",change);
//}
- (NSMutableArray *)dataArr
{
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}
- (UITableView *)table
{
    if (!_table) {
        _table = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, WIDTH, HEIGHT-64-51) style:UITableViewStylePlain];
        _table.delegate = self;
        _table.dataSource = self;
        _table.showsVerticalScrollIndicator = NO;
        _table.separatorInset=UIEdgeInsetsMake(0,15,0,15);
        _table.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            
            [self getList];
        }];
        [_table registerNib:[UINib nibWithNibName:@"ServerCell" bundle:nil] forCellReuseIdentifier:@"ServerCell"];
    }
    return _table;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"服务";
    self.automaticallyAdjustsScrollViewInsets = NO;
    _nextKey = 0;
    _isError = NO;
    self.headerVi = self.scroll;
 //   _dataDic = [NSDictionary dictionary];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(startCollect) name:@"startcollect" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(endCollect) name:@"endcollect" object:nil];

    _haveClicked = NO;
    _slideArr = [NSMutableArray array];
    _loadingArr = [NSMutableArray array];
    
    if (IPHONE6) {
      
        _addHeight = 10;
    }else if (IPHONE6P){
    
        _addHeight = 20;
    }else{
        _addHeight = 0;
    }
    [self getTheLaunchImage];

    
    if ([SHOWAD boolValue]) {
        //[self showBtn];
        
        [MyCar isBus:^(bool isbus) {
            NSLog(@"qqqqq%d",isbus);
            if (isbus) {
                [[NSUserDefaults standardUserDefaults]setObject:@(1) forKey:@"isbus"];
                
            }else
            {
                [[NSUserDefaults standardUserDefaults]setObject:@(0) forKey:@"isbus"];
            }
            
            [[MyAd sharedMyad]getDataWithTag:@"server" back:^(NSDictionary *dic) {
                _isError = NO;
                
                [self analyzeData:dic];
            } error:^(NSError *error,NSDictionary *di) {
                _isError = YES;
                [self analyzeData:di];
            }];
            
            
        }];
        
    }else{
//        [self createScrollView];
//        [self createPageController];
        
        if (self.dataDic.count) {
            NSLog(@"%@",self.dataDic);
            [self analyzeData:self.dataDic];
        }else{
            UIImageView *ima = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, SCALEY*(179))];
            CGRect rect = CGRectMake(0, 0, WIDTH, SCALEY*(179));
            ima.image = [UIImage imageWithCGImage:CGImageCreateWithImageInRect(_launchimage.CGImage, rect)];
            //ima.image = [UIImage imageNamed:@"APP加载页_meitu_4_meitu_1.jpg"];
            [self.scroll addSubview:ima];
        }
    }
    [self getList];
    //[self autoLogin];
    
}

- (BOOL)valiMobile:(NSString *)mobilePhone {
    //验证手机号
    //移动号段正则表达式
    NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
    //联通号段正则表达式
    NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
    //电信号段正则表达式
    NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
    NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
    BOOL isMatch1 = [pred1 evaluateWithObject:mobilePhone];
    NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
    BOOL isMatch2 = [pred2 evaluateWithObject:mobilePhone];
    NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
    BOOL isMatch3 = [pred3 evaluateWithObject:mobilePhone];
    
    if (isMatch1 || isMatch2 || isMatch3){
        return YES;
    }
    return NO;
}
- (void)getList
{
    if (_nextKey == 1000) {
        [self.view Message:@"亲,已经到底了" HiddenAfterDelay:1];
        [self.table.footer endRefreshing];
        return;
    }
    NSString *url = SERVICELIST;
//    if ([ISBUS boolValue]) {
//        
//    }else{
//        url = SERVICELIST;
//    }
    
    NSDictionary *parameter = @{@"next_key":@(_nextKey),@"page_size":@(10)};
    
    [MyAFN POST:url parameters:parameter block:^(id responseObject) {
        
        NSDictionary *response = responseObject;
        if ([[response objectForKey:@"status"]integerValue]) {
            
            if ([[response objectForKey:@"next_key"]integerValue]) {
                _nextKey = [[response objectForKey:@"next_key"] integerValue];
            }else{
                _nextKey = 1000;
            }
            [[EGOCache globalCache]setObject:response forKey:NSStringFromClass([self class])];
            [self analyzeList:response];
            [_table.footer endRefreshing];
        }
    } error:^(NSError *error) {
        NSDictionary *data = (NSDictionary *)[[EGOCache globalCache]objectForKey:NSStringFromClass([self class])];
        [self analyzeList:data];
        [_table.footer endRefreshing];
    } fromController:nil];
}

- (void)analyzeList:(NSDictionary *)dic
{
    NSMutableArray *newArr = [NSMutableArray array];
    for (NSDictionary *di in [dic objectForKey:@"serverList"]) {
        ServerModel *model = [[ServerModel alloc]init];
        [model setValuesForKeysWithDictionary:di];
        [newArr addObject:model];
    }
    [self checkData:newArr];
    [self.dataArr addObjectsFromArray:newArr];
    [self.table reloadData];
}

- (void)checkData:(NSMutableArray *)arr
{
    for (ServerModel *model in self.dataArr) {
        for (ServerModel *newModel in arr) {
            if ([newModel.serverId isEqualToString:model.serverId]) {
                [arr removeAllObjects];
                break;
            }
        }
    }
}

- (void)autoLogin
{
    if (!USERID) {
        return;
    }
    NSDictionary *dic = @{@"login_id":USERID};;
    
//    if ([self valiMobile:USERID]) {
//        dic = @{@"login_id":USERID};
//    }else{
//        dic = @{@"login_id":USERID};
//    }
    [MyAFN POST:USERINFO parameters:dic block:^(id responseObject) {
        NSDictionary *response = responseObject;
        
        if ([response objectForKey:@"status"]) {
            
            [[Myuser sharedUser]setValuesForKeysWithDictionary:response];
            
            NSString *loginid;
            if ([response objectForKey:@"login_id"]) {
                
                loginid = [response objectForKey:@"login_id"];
            }else{
                
                loginid = [response objectForKey:@"uuid"];
            }
            [[NSUserDefaults standardUserDefaults]setObject:loginid forKey:@"userid"];
            [Myuser sharedUser].login_id = loginid;
            
            //            [[NSUserDefaults standardUserDefaults]setObject:[MyMD5 md5:@"123456"] forKey:@"userpwd"];
            
            NSString *myname;
            if ([response objectForKey:@"name"]) {
                myname = [response objectForKey:@"name"];
                
            }
            [Myuser sharedUser].name = myname;
            
            NSString *url;
            if ([response objectForKey:@"photo"]) {
                
                //url = [NSString stringWithFormat:@"%@?url=%@",GETICON,[response objectForKey:@"photo"]];
                url = [response objectForKey:@"photo"];
            }
            [[NSUserDefaults standardUserDefaults]setObject:url forKey:@"usericon"];
            [Myuser sharedUser].icon = url;
            
        }else{
            [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"userid"];
            [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"usericon"];
            [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"username"];
            [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"userpwd"];
        }
        
    } error:^(NSError *error) {
        
        [[Myuser sharedUser]cleanUser];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"changeUserinfo" object:nil];
        [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"userid"];
        [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"usericon"];
        [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"username"];
        [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"userpwd"];
        
    } fromController:nil];
}

- (void)startCollect
{
    NSLog(@"----------------start");
    [self workBlock:scrollView];
}

- (void)endCollect
{
    NSLog(@"----------------end");
    
    [self restBlock:scrollView];
}

- (void)analyzeData:(NSDictionary *)data
{
    for (NSDictionary *dic in [data objectForKey:@"bannerList"]) {
        
        BannerModel *model = [[BannerModel alloc]init];
        [model setValuesForKeysWithDictionary:dic];
        
        if (model.path.integerValue == 0) {
            [_loadingArr addObject:model];
        }else if((model.path.integerValue >0)&(model.path.integerValue<=5)){
            [_slideArr addObject:model];
        }
    }
    //[self showClose];
    
    //scrollView = [[MyAd sharedMyad]createHeaderview:_slideArr target:self];
    [self createHeaderview:_slideArr];
    scrollView.y = 0;
    scrollView.height = HEIGHT-64-51- SCALEX*(278);
    [self workBlock:scrollView];
    [self.scroll addSubview:scrollView];
    
    [self.view addSubview:self.table];
    self.scroll.height = HEIGHT-64-51;
    NSLog(@"%f  %f",SCALEX, SCALEY);
    //self.scroll.height = self.scroll.height * SCALEX;
    self.table.tableHeaderView = self.headerVi;
   // [self createHeaderview:_slideArr];

}
- (void)createHeaderview:(NSArray *)arr
{
    //滑动视图
    if (arr.count) {
        NSMutableArray *temArr = [NSMutableArray array];
        for (BannerModel *model in arr) {
            NSString *url;
            if ([ISBUS boolValue]) {
                url = [NSString stringWithFormat:@"%@%@",CAR_URL,model.home_pic];
            }else{
                url = model.home_pic;
            }
            
            [temArr addObject:url];
        }
        
        scrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-64-51- SCALEX*(280)) imageURLStringsGroup:temArr];
        
    }else{
        
        CGRect rect = CGRectMake(0, 130*SCALEY, WIDTH, SCALEY*(179));
        
        UIImage *image = [UIImage imageWithCGImage:CGImageCreateWithImageInRect(_launchimage.CGImage, rect)];
        arr = @[image];
        //arr=@[[UIImage imageNamed:@"APP加载页_meitu_4_meitu_1.jpg"]];
        //scrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, WIDTH, SCALEY*(280)) imagesGroup:arr];
        scrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-64-51- SCALEX*(280)) imagesGroup:arr];
    }
    
    if (arr.count == 1) {
        scrollView.autoScroll = NO;
        scrollView.infiniteLoop = NO;
    }
    [self workBlock:scrollView];
    
    //设置需要的属性
    //view2.showPageControl = NO;
    scrollView.pageControlStyle = SDCycleScrollViewPageContolStyleAnimated;
    scrollView.autoScrollTimeInterval = 5;
     scrollView.delegate = self;
    // scrollView.titlesGroup = strArr;
    scrollView.dotColor = [UIColor whiteColor];
    
//    scrollView.alpha = 0;
    [self.scroll addSubview:scrollView];
    [self.scroll bringSubviewToFront:scrollView];
    //CGRect rect = self.scroll.frame;
    
}

- (void)workBlock:(SDCycleScrollView *)view
{
    NSLog(@"出现%lu",self.tabBarController.selectedIndex);
    if (self.tabBarController.selectedIndex != 2) {
        return;
    }
    
    __weak NSArray *slide = _slideArr;
    view.getContentOffset = ^(float offset){
        
        if (!_isError&&_slideArr.count) {
            
            int i;
            
            if (offset == 0) {
                
                i = 0;
            }else{
                int index = offset/WIDTH;
                i = index%_slideArr.count ;
            }
        
            NSLog(@"++++%d",i);
            if (i<_slideArr.count) {
                BannerModel *model = slide[i];
                [MyAd collectShowAd:model];
            }
        }
        
    };
}

- (void)restBlock:(SDCycleScrollView *)view
{
    if (view) {
        view.getContentOffset = ^(float offset){
            
            
        };
    }
    
}

- (BOOL)prefersStatusBarHidden
{
    if (_statusBarHide) {
        return YES;
    }else{
        return NO;
    }
}

- (void)showBtn
{
    _statusBarHide = YES;
    [self prefersStatusBarHidden];
    
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = YES;
    
    _shouldHide = YES;
    
    _adIma = [[UIImageView alloc]initWithFrame:SCREEN];
    _adIma.userInteractionEnabled = YES;
    
    
    if ([SHOWAD boolValue]) {
        
    _isThirdAD = YES;
    _adIma.image = _launchimage;
    [self.view addSubview:_adIma];
    [self.view bringSubviewToFront:_adIma];
    }
}

- (void)showClose
{
    UIImage *ima = _launchimage;
    
    if (!_loadingArr.count) {
//有网没广告
        [self dismissBtn];
        
        AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        fK = delegate.window;
        
        
        if ([SHOWAD boolValue]) {
           
            if (!_isError) {
                _statusBarHide = YES;
                [self prefersStatusBarHidden];
            }
            
            _splash = [[GDTSplashAd alloc] initWithAppkey:GGTID placementId:@"7000812135592948"];
            _splash.backgroundColor = [UIColor colorWithPatternImage:_launchimage];
            _splash.delegate = self;
            
            
            //设置开屏拉取时长限制，若超时则不再展示广告
            _splash.fetchDelay = 5;
            
            //拉取并展示
            [_splash loadAdAndShowInWindow:fK];
        }
        
       // _adIma.image = [UIImage imageNamed:@"广告2.jpg"];
        
//        [_adIma addSubview:imaview];
//        [self performSelector:@selector(dismissBtn) withObject:nil afterDelay:DELAYTIME];
        return;
    }
    BannerModel *model = _loadingArr[0];
    NSString *str;
    if ([ISBUS boolValue]) {
        str = [NSString stringWithFormat:@"%@%@",CAR_URL,model.home_pic];
    }else{
        str = model.home_pic;
    }
    [_adIma sd_setImageWithURL:[NSURL URLWithString:str] placeholderImage:ima completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        
        [self performSelector:@selector(dismissBtn) withObject:nil afterDelay:DELAYTIME];
        
        if (!image) {
            
            //_adIma.image = [UIImage imageNamed:@"广告2.jpg"];
        }else{
            
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(showAd)];
            [_adIma addGestureRecognizer:tap];
            
            UIVisualEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
            UIVisualEffectView *effectvi = [[UIVisualEffectView alloc]initWithEffect:effect];
            effectvi.frame = CGRectMake(WIDTH - 70, 30, 60, 30);
            effectvi.layer.cornerRadius = 10;
            effectvi.clipsToBounds = YES;
            [_adIma addSubview:effectvi];
            
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            [btn setFrame:CGRectMake(0, 0, 60, 30)];
            [btn setTitle:@"跳过广告" forState:UIControlStateNormal];
            btn.titleLabel.font = [UIFont systemFontOfSize:13];
            //btn.backgroundColor = [UIColor colorWithRed:238/255.0 green:238/255.0 blue:238/255.0 alpha:1];
            btn.backgroundColor = [UIColor clearColor];
            btn.layer.cornerRadius = 10;
            [btn addTarget:self action:@selector(dismissBtn) forControlEvents:UIControlEventTouchUpInside];
            [effectvi addSubview:btn];
            
            [MyAd collectShowAd:model];
        }
        UIImageView *imaview = [[UIImageView alloc]initWithFrame:CGRectMake(0, HEIGHT - WIDTH*2/7, WIDTH, WIDTH*2/7)];
        imaview.image = [UIImage imageNamed:@"广告.jpg"];
        [_adIma addSubview:imaview];
    }];
    
//    UIImageView *imaview = [[UIImageView alloc]initWithFrame:CGRectMake(0, HEIGHT - WIDTH*2/7, WIDTH, WIDTH*2/7)];
//    imaview.image = [UIImage imageNamed:@"广告.jpg"];
//    [_adIma addSubview:imaview];
}
- (void)getTheLaunchImage
{
//    NSString *launchImage = nil;
//    NSArray* imagesDict = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchImages"];
//    for (NSDictionary* dict in imagesDict)
//    {
//        CGSize imageSize = CGSizeFromString(dict[@"UILaunchImageSize"]);
//        
//        if (CGSizeEqualToSize(imageSize, SCREEN.size))
//        {
//            launchImage = dict[@"UILaunchImageName"];
//        }
//    }
//    _launchimage = [self imageWithImage:[UIImage imageNamed:launchImage] scaledToSize:CGSizeMake(WIDTH, HEIGHT)];
    
    getLaunchImage(_launchimage);
    //_launchimage = [self imageWithImage:[UIImage imageNamed:imaurl] scaledToSize:CGSizeMake(WIDTH, HEIGHT)];
//    Ivar
//    objc_getAssociatedObject(<#id object#>, <#const void *key#>)
//    objc_setAssociatedObject(self, <#const void *key#>, <#id value#>, <#objc_AssociationPolicy policy#>)
}

-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    
    // Return the new image.
    return newImage;
}

- (void)dismissBtn
{
    [UIView animateWithDuration:0.5 animations:^{
        scrollView.alpha = 1;
        _adIma.alpha = 0;
    
        
        _statusBarHide = NO;
    } completion:^(BOOL finished) {
        
        [self prefersStatusBarHidden];
        
        _shouldHide = NO;
        
        if (!_haveClicked) {
                
            self.navigationController.navigationBarHidden = NO;
            self.tabBarController.tabBar.hidden = NO;
        }else{
            self.navigationController.navigationBarHidden = YES;
            self.tabBarController.tabBar.hidden = YES;
        }
        
        
        [_adIma removeFromSuperview];
        if (!_haveClicked) {
            if (scrollView.shouldGetoffset) {
                scrollView.shouldGetoffset = YES;
            }
        }
        
    }];
}

- (void)showAd
{
    BannerModel *model = _loadingArr[0];
    [MyAd collectClickAd:model];
    
    _haveClicked = YES;
    
    [self dismissBtn];
    AdViewController *ad = [[AdViewController alloc]init];
    ad.urlstr = model.href;
    [self.navigationController pushViewController:ad animated:YES];
}

- (IBAction)foodClick:(id)sender {
    [self gotoDetail:@"http://u.ctrip.com/union/CtripRedirect.aspx?TypeID=2&Allianceid=301467&sid=771033&OUID=&jumpUrl=http%3A%2F%2Fm.ctrip.com%2Fwebapp%2Fyou%2Ffoods%2Fhefei196.html%3FAllianceid%3D301467%26sid%3D771033%26OUID%3D%26MultiUnionSupport%3Dtrue"];
}
- (IBAction)filmClick:(id)sender {
    NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];
    [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
    [self.view Message:@"暂时没有服务,敬请期待" HiddenAfterDelay:1];
}
- (IBAction)hotelClick:(id)sender {
    [self gotoDetail:@"http://u.ctrip.com/union/CtripRedirect.aspx?TypeID=2&Allianceid=301467&sid=771033&OUID=&jumpUrl=http%3A%2F%2Fm.ctrip.com%2Fwebapp%2Fhotel%2F%3FAllianceid%3D301467%26sid%3D771033%26OUID%3D%26MultiUnionSupport%3Dtrue"];
}
- (IBAction)KTVClick:(id)sender {
    
    [self.view Message:@"暂时没有服务,敬请期待" HiddenAfterDelay:1];
}
- (IBAction)houseClick:(id)sender {
    [self.view Message:@"暂时没有服务,敬请期待" HiddenAfterDelay:1];
}
- (IBAction)travelClick:(id)sender {
    [self gotoDetail:@"http://u.ctrip.com/union/CtripRedirect.aspx?TypeID=2&Allianceid=301467&sid=771033&OUID=&jumpUrl=http%3A%2F%2Fm.ctrip.com%2Fwebapp%2Ftour%2Fvacations%3Ffrom%3Dctrip_home%3FAllianceid%3D301467%26sid%3D771033%26OUID%3D%26MultiUnionSupport%3Dtrue"];
}
- (IBAction)buyticketClick:(id)sender {
    [_descScroll removeFromSuperview];
    if(!_carBtn&!_planBtn){
        _carBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_carBtn setBackgroundImage:[UIImage imageNamed:@"汽车票"] forState:UIControlStateNormal];
        [_carBtn addTarget:self action:@selector(busticket:) forControlEvents:UIControlEventTouchUpInside];
        
        _planBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_planBtn setBackgroundImage:[UIImage imageNamed:@"飞机票"] forState:UIControlStateNormal];
        [_planBtn addTarget:self action:@selector(planticket:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    if (!_backView) {
        _backView = [[UIView alloc]initWithFrame:SCREEN];
        
        _backView.backgroundColor = [[UIColor grayColor] colorWithAlphaComponent:0.8];
        _backView.frame = CGRectMake(WIDTH/2, HEIGHT/2, 0, 0);
    }
    
    [_backView addSubview:_carBtn];
    [_backView addSubview:_planBtn];
    [self.view addSubview:_backView];
    
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = YES;
    
    _carBtn.frame = CGRectMake(WIDTH/2 - 90, HEIGHT,60, 60);
    _planBtn.frame = CGRectMake(WIDTH/2+30, HEIGHT, 60, 60);
    
    [UIView animateWithDuration:0.3 animations:^{
        
        _backView.frame = FRAME;
    } completion:^(BOOL finished) {
        
        [UIView animateWithDuration:0.3 delay:0.1 usingSpringWithDamping:0.5 initialSpringVelocity:10 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            
            _carBtn.frame = CGRectMake(WIDTH/2 - 90, HEIGHT/2 - 30,60, 60);
        } completion:^(BOOL finished) {
            
        }];
        
        [UIView animateWithDuration:0.3 delay:0.2 usingSpringWithDamping:0.5 initialSpringVelocity:10 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            
            _planBtn.frame = CGRectMake(WIDTH/2 +30, HEIGHT/2 - 30,60, 60);
        } completion:^(BOOL finished) {
            
        }];
    }];
    
    
}
- (void)busticket:(UIButton *)btn
{
    [self gotoDetail:@"http://u.ctrip.com/union/CtripRedirect.aspx?TypeID=2&Allianceid=301467&sid=771033&OUID=&jumpUrl=http%3A%2F%2Fm.ctrip.com%2Fwebapp%2Fbus%2F%3FAllianceid%3D301467%26sid%3D771033%26OUID%3D%26MultiUnionSupport%3Dtrue"];
}
- (void)planticket:(UIButton *)btn
{
    [self gotoDetail:@"http://u.ctrip.com/union/CtripRedirect.aspx?TypeID=2&Allianceid=301467&sid=771033&OUID=&jumpUrl=http%3A%2F%2Fm.ctrip.com%2Fhtml5%2Fflight%2Fmatrix.html%3FAllianceid%3D301467%26sid%3D771033%26OUID%3D%26MultiUnionSupport%3Dtrue"];
}

- (IBAction)otherClick:(id)sender {
    //NSLog(@"aaaa");
    [self.view Message:@"暂时没有服务,敬请期待" HiddenAfterDelay:1];
}


- (IBAction)rentcarClick:(id)sender {
    [self gotoDetail:@"http://u.ctrip.com/union/CtripRedirect.aspx?TypeID=2&Allianceid=301467&sid=771033&OUID=&jumpUrl=http%3A%2F%2Fm.ctrip.com%2Fwebapp%2Fcars%2Fisd%2Fisd%3Fsecondarypage%3D1%3FAllianceid%3D301467%26sid%3D771033%26OUID%3D%26MultiUnionSupport%3Dtrue"];
}
- (IBAction)taketaxiClick:(id)sender {
    [self gotoDetail:@"http://u.ctrip.com/union/CtripRedirect.aspx?TypeID=2&Allianceid=301467&sid=771033&OUID=&jumpUrl=http%3A%2F%2Fm.ctrip.com%2Fwebapp%2Fcar%2Frtn%2Frtn%3Fsecondarypage%3D1%26isTaxi%3D0%26isBooking%3D0%3FAllianceid%3D301467%26sid%3D771033%26OUID%3D%26MultiUnionSupport%3Dtrue"];
}

- (void)gotoDetail:(NSString *)str
{
    [_backView removeFromSuperview];
    HomeDetailViewController *detail = [[HomeDetailViewController alloc]init];
   
    detail.urlstr = str;
    [self.navigationController pushViewController:detail animated:YES];
}


- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    NSLog(@"点击%ld",(long)index);
    if (!_slideArr.count) {
        return;
    }
    BannerModel *model = [_slideArr objectAtIndex:index];
    
    [MyAd collectClickAd:model];
    
    AdViewController *ad = [[AdViewController alloc]init];
    if (![model.href hasPrefix:@"http://"]&&![model.href hasPrefix:@"https://"]) {
        model.href = [NSString stringWithFormat:@"http://%@",model.href];
    }
    ad.urlstr = model.href;
    [self.navigationController pushViewController:ad animated:YES];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if(_isThirdAD){
        
        return;
    }
    
    UITouch *tou = [touches anyObject];
    if (tou.view != _carBtn | tou.view != _planBtn) {
        
        [_carBtn removeFromSuperview];
        [_planBtn removeFromSuperview];
        [_backView removeFromSuperview];
        self.navigationController.navigationBarHidden = NO;
        self.tabBarController.tabBar.hidden = NO;
        
        _backView.frame = CGRectMake(WIDTH/2, HEIGHT/2, 0, 0);
        if (_desc) {
            _desc.width = 0;
            _desc.height = 0;
        }
    }
    
    [self.view endEditing:YES];
}

//- (void)scrollViewDidScroll:(UIScrollView *)scrollVie
//{
//    // 取出水平方向上滚动的距离
//    if (scrollVie != scrollVi) {
//        return;
//    }
//    CGFloat offsetX = scrollVie.contentOffset.x;
//    
//    // 求出页码
//    double pageDouble = offsetX / scrollView.frame.size.width;
//    int pageInt = (int)(pageDouble + 0.5);
//    self.pageControl.currentPage = pageInt;
//}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (_shouldHide) {
        
        self.navigationController.navigationBarHidden = YES;
        self.tabBarController.tabBar.hidden = YES;
    }else{
        self.navigationController.navigationBarHidden = NO;
        self.tabBarController.tabBar.hidden = NO;
        
    }
    
    
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [self restBlock:scrollView];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (scrollView) {
        
        [self workBlock:scrollView];
        
        if (scrollView.shouldGetoffset) {
            scrollView.shouldGetoffset = YES;
        }
    }
}
- (void)splashAdWillPresentFullScreenModal:(GDTSplashAd *)splashAd
{
    
    NSLog(@"%s",__FUNCTION__);
}
/**
 *  点击以后全屏广告页已经被关闭
 */
- (void)splashAdDidDismissFullScreenModal:(GDTSplashAd *)splashAd
{

    NSLog(@"%s",__FUNCTION__);
}
-(void)splashAdSuccessPresentScreen:(GDTSplashAd *)splashAd
{
    _statusBarHide = NO;
    [self prefersStatusBarHidden];
    _isThirdAD = NO;
    NSLog(@"%s",__FUNCTION__);
}

-(void)splashAdFailToPresent:(GDTSplashAd *)splashAd withError:(NSError *)error
{
    _statusBarHide = NO;
    [self prefersStatusBarHidden];
    self.navigationController.navigationBarHidden = NO;
    self.tabBarController.tabBar.hidden = NO;
    NSLog(@"%s%@",__FUNCTION__,error);
}
-(void)splashAdClicked:(GDTSplashAd *)splashAd
{
    NSLog(@"%s",__FUNCTION__);
}

-(void)splashAdApplicationWillEnterBackground:(GDTSplashAd *)splashAd
{
    NSLog(@"%s",__FUNCTION__);
}

-(void)splashAdClosed:(GDTSplashAd *)splashAd
{
    
    NSLog(@"%s",__FUNCTION__);
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ServerModel *model = [self.dataArr objectAtIndex:indexPath.row];
    ServerCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ServerCell" forIndexPath:indexPath];
    
    [cell showModel:model];
    return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArr.count;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ServerModel *model = [self.dataArr objectAtIndex:indexPath.row];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (!_backView) {
        _backView = [[UIView alloc]initWithFrame:SCREEN];
        
        _backView.backgroundColor = [[UIColor grayColor] colorWithAlphaComponent:0.8];
        _backView.frame = CGRectMake(WIDTH/2, HEIGHT/2, 0, 0);
    }
    [self.view addSubview:_backView];
    
    if (!_desc) {
        _desc = [[UILabel alloc]init];
        _desc.numberOfLines = 0;
    }
    if (!_descScroll) {
        _descScroll = [[UIScrollView alloc]init];
        _descScroll.backgroundColor = [UIColor whiteColor];
    }
    if ([model.remark rangeOfString:@"&quot;"].location !=NSNotFound) {
        
        NSString *str = [model.remark stringByReplacingOccurrencesOfString:@"&quot;" withString:@"\""];
        _desc.text = str;
    }else if([model.remark rangeOfString:@"&ldquo;"].location !=NSNotFound){
        
        NSString *str = [model.remark stringByReplacingOccurrencesOfString:@"&ldquo;" withString:@"“"];
        str = [str stringByReplacingOccurrencesOfString:@"&rdquo;" withString:@"”"];
        
        _desc.text = str;
        
    }else{
        
        _desc.text = model.remark;
    }
    
    CGSize size = sizeForLabel(_desc, WIDTH-100);
    
    [UIView animateWithDuration:0.3 animations:^{
        
        _backView.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
        
    } completion:^(BOOL finished) {
        
        [UIView animateWithDuration:0.5 animations:^{
            if (size.height>HEIGHT-300) {
                _descScroll.frame = CGRectMake(WIDTH/2-size.width/2-10, HEIGHT/2-(HEIGHT-300)/2-10, size.width+20, HEIGHT-300+20);
                _descScroll.contentSize = CGSizeMake(size.width, size.height+20);
                _descScroll.contentOffset = CGPointZero;
            }else{
                _descScroll.frame = CGRectMake(WIDTH/2-size.width/2-10, HEIGHT/2-size.height/2-10, size.width+20, size.height+20);
                _descScroll.contentSize = CGSizeZero;
            }
            _desc.frame = CGRectMake(10, 10, size.width, size.height);
        }];
    }];
    
    [_descScroll addSubview:_desc];
    [_backView addSubview:_descScroll];
    
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = YES;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 30)];
    view.backgroundColor = [UIColor whiteColor];
    
    UIView *vi = [[UIView alloc]initWithFrame:CGRectMake(0, 1, 5, 28)];
    vi.backgroundColor = RGBcolor(255, 90, 47);
    [view addSubview:vi];
    
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(15, 29, WIDTH-30, 1)];
    line.backgroundColor = RGBcolor(229, 229, 229);
    [view addSubview:line];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 100, 30)];
    label.text = @"衣食住行";
    font(label, 14);
    [view addSubview:label];
    return view;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 30;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
